﻿using ConfExpert.Forms.Base;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;

using DevTeamIT;
using Extensions;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Windows.Forms;

namespace ConfExpert.Forms.Sistem
{
    public partial class Profil : XForm
    {
        public Profil()
        {
            InitializeComponent();
        }

        Dictionary<string, int> prfile = new Dictionary<string, int>();
        string version = "ENG";
        BindingSource bs;
        private void Profil_Load(object sender, EventArgs e)
        {
            prfile.Add("ENG", 3037);
            prfile.Add("ITA", 11313);

            bs = new BindingSource(ds, "Sent");
            InitGridView(gvProfil, bs);
            gvProfil.OptionsBehavior.Editable = false;
            GetDetails("Sent", "GetSent", string.Empty, string.Empty, string.Empty, null);
            gvProfil.BestFitColumns();

            btnSend.Enabled = false;
            btnSend.ItemClick += BtnSend_ItemClick;
            mruEmail.EditValueChanged += MruEmail_EditValueChanged;


            btnUpload.Visibility = ytk(65) ? DevExpress.XtraBars.BarItemVisibility.Always : DevExpress.XtraBars.BarItemVisibility.Never;
            btnUpload.ItemClick += BtnUpload_ItemClick;
            btnView.ItemClick += BtnView_ItemClick;

            ((RepositoryItemComboBox)cmbVersion.Edit).TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            cmbVersion.EditValueChanged += CmbVersion_EditValueChanged;
            cmbVersion.EditValue = "ENG";
        }


        private void CmbVersion_EditValueChanged(object sender, EventArgs e)
        {
            version = cmbVersion.EditValue.ToStr();
            if (version != string.Empty)
            {
                DataTable t = Session.DataManager.ExecuteDataTable("GetDoc", prfile[version]);
                FileToSend = ByteArrayToFile3(t.Rows[0]["DosyaAdi"].ToString(), t.Rows[0]["BLOB"] as byte[]);
            }
        }

        private void BtnView_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo.FileName = FileToSend;
            process.Start();
        }

        private void BtnUpload_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                using (OpenFileDialog openFileDialog1 = new OpenFileDialog())
                    if (openFileDialog1.ShowDialog() == DialogResult.OK)
                        if (openFileDialog1.OpenFile() != null)
                        {
                            string FileName = Path.GetFileName(openFileDialog1.FileName),
                                Extension = Path.GetExtension(openFileDialog1.FileName);
                            //md5 = MD5.GetHashFromFile(openFileDialog1.FileName);
                            byte[] bArr = FileManager.Read(openFileDialog1.FileName);
                            ExecuteNonQuery("UpdDoc", prfile[version], openFileDialog1.SafeFileName, Extension, bArr, WhoAmI, "");
                            XtraMessageBox.Show("Profil güncellendi.");
                        }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }




        string FileToSend;

        private void MruEmail_EditValueChanged(object sender, EventArgs e)
        {
            btnSend.Enabled = (mruEmail.EditValue.ToStr() != string.Empty);
        }

        private void BtnSend_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                MailAddress SendFrom = new MailAddress(Session.CurrentUser.Email /*"orhan.aykut@karbel.com"*/);
                MailAddress SendTo = new MailAddress(mruEmail.EditValue.ToStr());

                MailMessage MyMessage = new MailMessage(SendFrom, SendTo);

                MyMessage.Subject = "Karbel company profile";
                MyMessage.IsBodyHtml = true;

                MyMessage.Body = "<p><div style=\"font-family:Arial\">Dear " + (teName.EditValue.ToStr() != string.Empty ? teName.EditValue.ToStr() : "sir/madam") + ",<p>Please find attached Karbel's company profile.<p>Kind regards,<p>" +
                    Session.CurrentUser.Name +
                    //teSender.Text + 
                    "</div>";
                //TR karakterler mailde bozulmaz mı?  UserInfo.Name'e dikkat!

                MailAddress copy = new MailAddress("esti.romano@karbel.com");
                MyMessage.CC.Add(copy);
                if (Session.CurrentUser.Email != "esti.romano@karbel.com")
                    MyMessage.CC.Add(Session.CurrentUser.Email);

                //MyMessage.Body = "<p><div style=\"font-family:Arial\">Dear " + (teName.Text != string.Empty ? teName.Text : "sir/madam") + ",<p>Attached is the company profile of Karbel for your info.<p>Best regards.<p>Cemal Karabel<br>Director, Karbel Co., Ltd.<br><br><br><p>P.S.:This message is sent via our application, automatically ;)</div>";

                //Attachment attachFile = new Attachment(@"C:\CompProfile-Eng.doc");
                Attachment attachFile = new Attachment(FileToSend);
                MyMessage.Attachments.Add(attachFile);

                SmtpClient emailClient = new SmtpClient("Karbelnt"); //exchange or smtp server goes here.

                emailClient.Credentials = CredentialCache.DefaultNetworkCredentials;

                emailClient.Send(MyMessage);

                GetDetails("Sent", "GetSent", teName.EditValue.ToStr(), mruEmail.EditValue.ToStr(), teNotes.EditValue.ToStr(), WhoAmI);
                gvProfil.BestFitColumns();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public string ByteArrayToFile3(string filePath, byte[] content)
        {
            string FullPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.InternetCache) + "\\" + filePath;
            using (FileStream fs = new FileStream(FullPath, FileMode.Create, FileAccess.Write))
            using (BinaryWriter bw = new BinaryWriter(fs))
            {
                bw.Write(content);
                bw.Flush();
            }


            return FullPath;
        }

    }
}